package cn.zswltech.gruul.web.api.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zhongjianwei on 2018/8/6.
 */
@Deprecated
public class LoginFilter implements Filter {



    private static final String SHOW_LOGIN_PATH = "/user/login";//显示登录页面
    //private static final String DO_LOGIN_PATH = "/user/login";//登录操作不能过滤掉
    private static final String LOGIN_TOKENID = "tokenId";//登录用户在session中的属性key -- session.setAttribute(key,value)

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {


    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;
        httpResp.setContentType("text/html");
        //判断是否是登录页面
        String servletPath = httpReq.getServletPath();
        //flag:若为登录页面的action路径 showloginPath/dologinPath,则赋值true，否则赋值false
        boolean flag = false;
        if (servletPath.equals(SHOW_LOGIN_PATH)) {
            chain.doFilter(request, response);
            flag = true;
            return;
        } else {   //如果不是登录页面，则需先判断用户是否已登录
            //String url = servletPath;
            Object loginId = httpReq.getHeader(LOGIN_TOKENID);
            if (loginId != null) {
                //如果不为空,则进行已登录处理
                chain.doFilter(request, response);
            } else {
                //如果为空,则进行未登录处理
                if (httpReq.getQueryString() != null) {
                    servletPath += "?" + httpReq.getQueryString();
                }
                httpReq.getSession().setAttribute("returnUri", servletPath);
                if (flag == false) {
                    httpReq.getRequestDispatcher(SHOW_LOGIN_PATH).forward(httpReq, httpResp);
                }
            }
        }

    }

    @Override
    public void destroy() {

    }
}
